from datetime import date, time, datetime
import logging
import bible
import bibleIndex
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
import os
from webbible.lib.base import BaseController, render
import json

log = logging.getLogger(__name__)

class SearchsController(BaseController):
    """REST Controller styled on the Atom Publishing Protocol"""
    def __init__(self):
	self.bibletext = 'webbible/save/kjb.txt'
	self.bibleloc = 'webbible/save/bible.sav'
	self.indexloc= 'webbible/save/index.sav'
	self.bookToNumLoc = 'webbible/save/bookToNum.sav'

    def init(self):
	b = bible.bible()
	b.init(self.bibletext,self.bibleloc,self.bookToNumLoc)
	bibleIndex.createIndex(self.indexloc,b)
		
    # To properly map this controller, ensure your config/routing.py
    # file has a resource setup:
    #     map.resource('search', 'searchs')
    def index(self, format='html'):
	#self.init()
	return os.path.abspath('.')
        """GET /searchs: All items in the collection"""
        # url('searchs')

    def create(self):
        """POST /searchs: Create a new item"""
        # url('searchs')

    def new(self, format='html'):
        """GET /searchs/new: Form to create a new item"""
        # url('new_search')

    def update(self, id):
        """PUT /searchs/id: Update an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(url('search', id=ID),
        #           method='put')
        # url('search', id=ID)

    def delete(self, id):
        """DELETE /searchs/id: Delete an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="DELETE" />
        # Or using helpers:
        #    h.form(url('search', id=ID),
        #           method='delete')
        # url('search', id=ID)

    def show(self, id, format='html'):
	print(request.params['json'])
	showReq = json.loads(str(id))
	ret = []
	i = 0
	bookNameToNum, bookNumToName = bible.loadBookNum(self.bookToNumLoc)

	for (b,c,v) in bibleIndex.lookup(self.indexloc,showReq['query']):
		if i == 7:
			break
		else:
 			i = i +1
		ret.append({'name':bookNumToName[b],'chapterNum':c, 'verseNum':v, 'verse':bible.lookup(self.bibleloc,b,c,v)})
	return json.dump(ret)

        """GET /searchs/id: Show a specific item"""
        # url('search', id=ID)

    def edit(self, id, format='html'):
        """GET /searchs/id/edit: Form to edit an existing item"""
        # url('edit_search', id=ID)




